Scope of Script Variables and Properties
The declaration of a variable or property identifier is the first valid occurrence of the identifier in a script. The form and location of the declaration determine how AppleScript treats the identifier in that script.The scope of a variable or property declaration is the extent to which AppleScript recognizes the declared identifier within a script. It is often convenient to limit the scope of a particular identifier to a single handler-that is, to treat the identifier as a local variable. After a local variable has served its purpose, its identifier no longer has any value associated with
it and can be used again for other purposes elsewhere in the script.If you want the value of a script to persist after a script is run, or if you wish
to use the same identifier in several different places in a script, you can declare it as either a script property or a global variable. AppleScript keeps track of properties and global variables across multiple handlers and script objects within a single script.This section describes how AppleScript interprets various forms of declarations within handlers, within script objects, and at the top level of a script. You should be familiar with the section "Run Handlers," which begins on page 243, before you read this section.
You can declare a property and set its initial value using a statement like this:
property x: 3The scope of a property declaration can be either a script object or an entire script. The value set by a property declaration is not reset each time the script
is run; instead, it persists until the script is recompiled.A global declaration is much the same as a property declaration except that it doesn't set an initial value:
global xThe scope of a global variable declaration can be limited to specific handlers or script objects or can extend throughout an entire script. Like the value of a property, the value of a global variable is not reset each time a script is run. However, the value of a global variable must be set by other statements in
the script.To set the value of any property or variable, use the Set command. (You can also use the Copy command for this purpose.)
set x to 3If the variable has not previously been declared, the Set or Copy command declares it as a local variable. But in some cases it is also necessary to declare
a local variable explicitly.
local xLike a global declaration, an explicit local declaration doesn't set an
initial value.The preceding examples represent the four basic forms for declaring variables and properties in AppleScript. The sections that follow describe how AppleScript interprets these four forms of declarations within handlers, within script objects, and at the top level of a script.
Subtopics
- Scope of Properties and Variables Declared at the Top Level of a Script
- Scope of Properties and Variables Declared in a Script Object
- Scope of Variables Declared in a Handler